#!/usr/bin/env bash
############################################################################
# https://www.cnblogs.com/fnlingnzb-learner/p/10657285.html
# 在脚本的开头，使用『#!/usr/bin/env bash』替换『#!/bin/sh』，防止在不同操作系统上『/bin/sh』链接到不同版本的默认shell;
############################################################################
# SCRIPTS_DIR="$( cd "$( dirname "$0" )" && pwd )"
# cd "${SCRIPTS_DIR}"
# if [ $? -ne 0 ]; then echo "[ERROR] coordinate: [$0][${LINENO}]"; exit 1; fi
############################################################################

while getopts ":e:s:b:l:d:x:h:" opt
do
    case $opt in
        e)
        exchange="${OPTARG}"
        ;;
        s)
        symbol="${OPTARG}"
        ;;
        b)
        begin="${OPTARG}"
        ;;
        l)
        last="${OPTARG}"
        ;;
        d)
        database="${OPTARG}"
        ;;
        x)
        xtrace="${OPTARG}"
        ;;
        :)
        echo "-e(exchange),-s(symbol),-b(begin),-l(last),-d(database),-x(xtrace),-h(help)";
        exit 0
        ;;
    esac
done

database=''"$([ -z "${database}" ] && echo "database.db" || echo "${database}")"

w_exchange="$([ -z "${exchange}" ] && echo "" || echo " AND exchange='${exchange}'")"
  w_symbol="$([ -z "${symbol}"   ] && echo "" || echo " AND symbol='${symbol}'")"
   w_begin="$([ -z "${begin}"    ] && echo "" || echo " AND datetime>='${begin}'")"
    w_last="$([ -z "${last}"     ] && echo "" || echo " AND datetime<='${last}'")"

declare -a array_column
idx=0
array_column[((idx++))]="symbol"
array_column[((idx++))]="exchange"
array_column[((idx++))]="datetime"
array_column[((idx++))]="interval"
array_column[((idx++))]="volume"
array_column[((idx++))]="turnover"
array_column[((idx++))]="open_interest"
array_column[((idx++))]="open_price"
array_column[((idx++))]="high_price"
array_column[((idx++))]="low_price"
array_column[((idx++))]="close_price"
columns=$(IFS=,; echo "${array_column[*]}")

[ -n "${xtrace}" ] && set -x

sqlite3 "${database}" "SELECT ${columns} FROM dbbardata WHERE 1=1${w_exchange}${w_symbol}${w_begin}${w_last} ORDER BY datetime ASC"
